<template>
  <ve-card
    :title="'合同编号：' + (record.contractNo || '-')"
    :sub-title="record.contractStatusName"
    :type="
      record.contractStatus == 1 || record.contractStatus == -2
        ? 'gray'
        : record.contractStatus == 2
        ? 'blue'
        : record.contractStatus == 3 || record.contractStatus == 10
        ? 'green'
        : record.contractStatus == 4 ||
          record.contractStatus == 5 ||
          record.contractStatus == 6 ||
          record.contractStatus == 7 ||
          record.contractStatus == 8 ||
          record.contractStatus == 11 ||
          record.contractStatus == -1
        ? 'pink'
        : record.contractStatus == 9
        ? 'purple'
        : 'gray'
    "
  >
    <ve-cell label="关联单号" @click="toOrder(record)"
      ><span style="color: rgba(24, 144, 255, 1)">{{ record.orderCode || '-' }}</span></ve-cell
    >
    <ve-cell label="所属门店">{{ record.siteName || '-' }}</ve-cell>
    <ve-cell label="业务类型">{{ record.orderTypeName || '-' }}</ve-cell>
    <ve-cell label="合同类型">{{ record.contractTypeName || '-' }}</ve-cell>
    <ve-cell label="合同模板名称">{{ record.templateName || '-' }}</ve-cell>
    <ve-cell label="客户类型">{{ record.leaseType == 1 ? '企业' : '个人' }}</ve-cell>
    <ve-cell label="客户信息">{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</ve-cell>

    <block v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
      <ve-cell label="承租方" class="tag-person">
        <view class="fs30 fw400 c1">{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.lesseeSignStatusName">
          <view :class="['tag', record.lesseeSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.lesseeSignStatusName || '-' }}</view>
        </view>

        <view class="copys" @click="copylink(record, '已将链接复制到剪切板')" v-if="usePermission('svmsapp:contract.CopySigningLink')">
          <image class="image-icon" src="@/static/icons/link.png" mode="widthFix"></image>
          <view class="copy-text">复制合同链接</view>
        </view>
      </ve-cell>

      <ve-cell label="出租方" class="tag-person">
        <view class="fs30 fw400 c1">{{ record.tenantName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.hireSignStatusName">
          <view :class="['tag', record.hireSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.hireSignStatusName || '-' }}</view>
        </view>
      </ve-cell>
    </block>
    <ve-cell label="签署短信条数">{{ record.msgNum != null ? record.msgNum : '-' }}</ve-cell>
    <ve-cell label="发起节点">{{ record.startNode || '-' }}</ve-cell>
    <ve-cell label="生成合同时间">{{ record.createTime || '-' }}</ve-cell>
    <ve-cell label="完成签署时间">{{ record.completeTime || '-' }}</ve-cell>
    <ve-cell label="发起人">{{ record.startPersonName || '-' }}</ve-cell>

    <ve-operate-list :operates="operates" :record="record" />
    <ve-popup :model-value="popupValue" @close="close" mode="bottom" :maskClose="true">
      <view class="add-popup">
        <view class="title">请选择</view>
        <ve-button class="button" size="default" @click="toPreview(record)" style="margin-bottom: 32rpx; background: #d5e3ff"
          >下载PDF文件</ve-button
        >
        <ve-button class="button" size="default" @click="toDownload(record)">下载JPG图片(合成长图)</ve-button>
      </view>
    </ve-popup>
  </ve-card>
</template>

<script setup>
  import { usePermission } from '@/hooks/usePermission'
  import { ref } from 'vue'
  import {
    downloadContractFileAPI,
    revokeAPI,
    nullifyAPI,
    getLesseeSignUrlAPI,
    deleteContractFileAPI,
    sendLesseeSignMsgAPI,
  } from '@/api/order/contract'

  defineProps({
    record: {
      type: Object,
    },
  })

  const popupValue = ref(false)
  const isDownload = ref(false)

  const emits = defineEmits(['resetRefresh'])

  // 链接复制
  const copylink = (record, tlt) => {
    // 获取到链接后 复制
    getLesseeSignUrlAPI({ id: record.id }).then((res) => {
      uni.setClipboardData({
        data: res.result,
        success: function () {
          uni.showToast({
            title: tlt,
            icon: 'none',
          })
        },
      })
    })
  }

  const operates = ref([
    // 签署中 已撤回 已完成 已作废
    //  已完成
    {
      label: '作废',
      permission: 'svmsapp:contract.InitiateCancellation',
      show: (record) => record.contractStatus == 3,
      method: (record) => {
        uni.showModal({
          title: '提示',
          content: '合同已完成签署，确认作废吗?',
          success: function (res) {
            if (res.confirm) {
              // 发起作废接口
              nullifyAPI({ id: record.id, payType: 0 }).then(() => {
                uni.showToast({
                  title: '操作成功',
                  icon: 'none',
                })
                emits('resetRefresh')
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '预览',
      permission: 'svmsapp:contract.Preview',
      method: (record) => {
        toPreview(record)
      },
    },
    // 签署中
    {
      label: '发送签署短信',
      permission: 'svmsapp:contract.message',
      show: (record) => record.contractStatus == 2,
      method: (record) => {
        uni.showModal({
          title: '提示',
          content: '发送签署短信会产生短信费用，请确认是否发送？',
          success: function (res) {
            if (res.confirm) {
              sendLesseeSignMsgAPI({ id: record.id }).then(() => {
                uni.showToast({
                  title: '操作成功',
                  icon: 'none',
                })
                emits('resetRefresh')
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '修改合同',
      permission: 'svmsapp:contract.edit',
      show: (record) => record.contractStatus == 2,
      method: (record) => {
        uni.navigateTo({
          url: `/pages/order/contract-content/edit-contract?id=${record.id}&orderType=${record.orderType}&orderId=${record.orderId}&contractType=${record.contractType}`,
        })
      },
    },
    // 签署中
    {
      label: '撤回',
      permission: 'svmsapp:contract.Withdraw',
      show: (record) => record.contractStatus == 2,
      method: (record) => {
        if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
          uni.showModal({
            title: '提示',
            content: '合同撤回后，承租方短信失效，无法完成签署，确认撤回吗？',
            success: function (res) {
              if (res.confirm) {
                revokeAPI({ id: record.id }).then(() => {
                  uni.showToast({
                    title: '操作成功',
                    icon: 'none',
                  })
                  emits('resetRefresh')
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
          revokeAPI({ id: record.id }).then(() => {
            uni.showToast({
              title: '操作成功',
              icon: 'none',
            })
            emits('resetRefresh')
          })
        }
      },
    },
    {
      label: '下载',
      permission: 'svmsapp:contract.download',
      show: (record) => record.contractStatus == 3 || record.contractStatus == 8,
      method: (record) => {
        openPopup()
      },
    },
  ])

  // 预览
  const toPreview = (record) => {
    downloadContractFileAPI({ id: record.id, contractFileType: 1 }).then((r) => {
      if (!r.result) {
        uni.showToast({
          title: '打开失败',
          icon: 'none',
        })
        return false
      }
      uni.downloadFile({
        url: r.result,
        success: function (res) {
          const filePath = res.tempFilePath
          uni.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
              // 销毁文件
              record.payType == 1 && deleteContractFileAPI({ contractFilePath: r.result })
            },
          })
        },
      })
    })
  }

  // 下载
  const toDownload = (record) => {
    if (!isDownload.value) {
      isDownload.value = true
      downloadContractFileAPI({ id: record.id, contractFileType: 2 }).then((r) => {
        isDownload.value = false
        if (!r.result) {
          uni.showToast({
            title: '下载失败',
            icon: 'none',
          })
          return false
        }
        uni.saveImageToPhotosAlbum({
          filePath: r.result,
          success: function () {
            uni.showToast({
              title: '已保存至相册',
              icon: 'none',
            })
            close()
          },
          fail: function (fail) {
            uni.showToast({
              title: fail.errMsg.includes('Permission') ? '无相册访问权限，无法下载' : '下载失败',
              icon: 'none',
            })
            close()
          },
        })
      })
    }
  }

  const openPopup = () => {
    popupValue.value = true
  }
  const close = () => {
    popupValue.value = false
  }

  // 跳转业务单详情
  const toOrder = (record) => {
    const { orderType, orderId } = record
    if (orderType == 1) {
      if (usePermission('svmsapp:order:short-order.view')) {
        uni.navigateTo({
          url: '/pages/order/short-order/detail/index?id=' + orderId,
        })
      }
    } else {
      if (usePermission('svmsapp:order:long-order.view')) {
        uni.navigateTo({
          url: '/pages/order/long-order/detail/index?id=' + orderId,
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .tag-person {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    view:nth-child(1) {
      max-width: 280rpx;
    }

    .person-flex-copy {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-left: 16rpx;
      .tag {
        padding: 0 16rpx;
        height: 40rpx;
        line-height: 38rpx;
        border-radius: 347rpx;
        font-size: 24rpx;
        margin-right: 24rpx;
      }
      .text-no {
        background: #fff7e8;
        color: #ff7d00;
      }
      .text-yes {
        background: #e8ffea;
        color: #00b42a;
      }
    }
  }

  .copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .image-icon {
      width: 28rpx;
      height: 28rpx;
      margin: 0 6rpx 0 0;
    }
    .copy-text {
      color: #3072f6;
      font-size: 26rpx;
      font-weight: 400;
    }
  }

  :deep(.ve-cell-content) {
    flex-wrap: wrap;
  }

  .add-popup {
    padding: 0 40rpx 96rpx 40rpx;
    .title {
      font-weight: 600;
      font-size: 36rpx;
      color: #191c27;
      line-height: 44rpx;
      text-align: center;
      padding: 32rpx 0 48rpx 0;
    }
  }
</style>
